package org.fintool.functional;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;

import org.fintool.beans.Scrip;
import org.fintool.beans.StockInfoMaster;
import org.fintool.beans.Tick;
import org.fintool.common.MathUtil;
import org.fintool.common.StockMasterUtil;

public class ScripCalculations {

	//Tamdem movements ,i.e one stock correlating other ,probably by day,try US exhange vs ASX/NSE
	//best day movements i.e which day in week is more likely for move and
	//average breadth of %age  move and least move %age to upside
	//Odd movements i.e same date rise ,or same day rise ,fall and move pattern for checking  possible spruiking
	//Volume based moves ,volume magic numbers and large volume spikes

	static void roughCalculation() throws Exception{
		FinanceUtilDay fd=new FinanceUtilDay();

		fd.updateQuotes("NCM","ASX");

		Scrip scrip=fd.getScripData("NCM","ASX");
		ArrayList tickerArrayList=scrip.getTickers();
		Iterator itr=tickerArrayList.iterator();
		Tick tick=null;

		while(itr.hasNext()){
			tick=(Tick)itr.next();
			System.out.println(tick.toString());


		}
	}



	public  String  compareScripCorrelation(Scrip scrip1,Scrip scrip2,double argsMinMove) throws Exception{

		StringBuffer resultBuffer=new StringBuffer();

		ArrayList tickerList1=scrip1.getTickers();
		ArrayList tickerList2=scrip2.getTickers();

		int startCountat=0;
		int adder=1;
		double minMove=argsMinMove;

		Tick tick1=null;
		Tick tick2=null;

		int noScrip2upMove=0;
		int matchedUpMove=0;
		double minGain=100.0;

		int noScrip2DownMove=0;
		int matchedDownMove=0;
		double minNegativeGain=-100.0;


		int totalCount=0;

		for(int i=startCountat;i<tickerList1.size();i++){
			totalCount+=1;
			if((i+adder)<tickerList2.size()){
				tick1=(Tick)tickerList1.get(i);
				tick2=(Tick)tickerList2.get(i+adder);


				if(tick2.getPercentageDiffPrevGainOnClose()>minMove){
					noScrip2upMove+=1;
					//if(tick1.getPercentageDiffPrevGainOnClose()>0.0){
					if(tick1.getPercentageDiffPrevGainMax()>0.0){
                       matchedUpMove+=1;
                       if(tick1.getPercentageDiffPrevGainMax()<minGain){
                    	   minGain=tick1.getPercentageDiffPrevGainMax();
                    	  // System.out.println(tick1+" \n "+tick2+"\n");
                       }
					}

				}


				if(tick2.getPercentageDiffPrevGainOnClose()<-(minMove)){
					noScrip2DownMove+=1;
					if(tick1.getPercentageDiffPrevNegativeMax()<0.0){
	                   matchedDownMove+=1;

	                   if(tick1.getPercentageDiffPrevNegativeMax()>minNegativeGain){
							 minNegativeGain=tick1.getPercentageDiffPrevNegativeMax();
	                     }
					}


				}
			}




		}




        resultBuffer.append(scrip1.getExchange()+":"+scrip1.getName()+" vs ");
        resultBuffer.append(scrip2.getExchange()+":"+scrip2.getName()+"  for Min move "+minMove+"\n ");
        resultBuffer.append("Total Count:"+totalCount);
        resultBuffer.append(" "+scrip2.getName()+" upmove - "+noScrip2upMove);
        resultBuffer.append(" , "+scrip1.getName()+" matched move - "+matchedUpMove );
        resultBuffer.append(" ,%age - "+MathUtil.getPortion((double)matchedUpMove,(double)noScrip2upMove) );
        resultBuffer.append(" , "+scrip1.getName()+" minimum - "+minGain );
        resultBuffer.append("\n" );
        resultBuffer.append(" "+scrip2.getName()+" downmove - "+noScrip2DownMove);
        resultBuffer.append(" , "+scrip1.getName()+" matched move - "+matchedDownMove );
        resultBuffer.append(" , "+scrip1.getName()+" minimum - "+minNegativeGain );
        resultBuffer.append("\n" );





		return resultBuffer.toString();


	}

	public  String  compareScripCorrelationNextDay(Scrip scrip1,Scrip scrip2,double argsMinMove) throws Exception{

		StringBuffer resultBuffer=new StringBuffer();

		ArrayList tickerList1=scrip1.getTickers();
		ArrayList tickerList2=scrip2.getTickers();

		int startCountat=0;
		int adder=1;
		double minMove=argsMinMove;

		Tick tick1=null;
		Tick tick2=null;

		int noScrip2upMove=0;
		int matchedUpMove=0;
		double minGain=100.0;

		int noScrip2DownMove=0;
		int matchedDownMove=0;
		double minNegativeGain=-100.0;


		int totalCount=0;

		for(int i=startCountat;i<tickerList1.size();i++){
			totalCount+=1;
			if((i+adder)<tickerList2.size()){
				tick1=(Tick)tickerList1.get(i);
				tick2=(Tick)tickerList2.get(i+adder);


				if(tick2.getPercentageDiffPrevGainOnClose()>minMove){
					noScrip2upMove+=1;
					//if(tick1.getPercentageDiffPrevGainOnClose()>0.0){
					if(tick1.getPercentageDiffPrevGainMax()>0.0){
                       matchedUpMove+=1;
                       if(tick1.getPercentageDiffPrevGainMax()<minGain){
                    	   minGain=tick1.getPercentageDiffPrevGainMax();
                    	  // System.out.println(tick1+" \n "+tick2+"\n");
                       }
					}

				}


				if(tick2.getPercentageDiffPrevGainOnClose()<-(minMove)){
					noScrip2DownMove+=1;
					if(tick1.getPercentageDiffPrevNegativeMax()<0.0){
	                   matchedDownMove+=1;

	                   if(tick1.getPercentageDiffPrevNegativeMax()>minNegativeGain){
							 minNegativeGain=tick1.getPercentageDiffPrevNegativeMax();
	                     }
					}


				}
			}




		}




        resultBuffer.append(scrip1.getExchange()+":"+scrip1.getName()+" vs ");
        resultBuffer.append(scrip2.getExchange()+":"+scrip2.getName()+"  for Min move "+minMove+"\n ");
        resultBuffer.append("Total Count:"+totalCount);
        resultBuffer.append(" "+scrip2.getName()+" upmove - "+noScrip2upMove);
        resultBuffer.append(" , "+scrip1.getName()+" matched move - "+matchedUpMove );
        resultBuffer.append(" ,%age - "+MathUtil.getPortion((double)matchedUpMove,(double)noScrip2upMove) );
        resultBuffer.append(" , "+scrip1.getName()+" minimum - "+minGain );
        resultBuffer.append("\n" );
        resultBuffer.append(" "+scrip2.getName()+" downmove - "+noScrip2DownMove);
        resultBuffer.append(" , "+scrip1.getName()+" matched move - "+matchedDownMove );
        resultBuffer.append(" , "+scrip1.getName()+" minimum - "+minNegativeGain );
        resultBuffer.append("\n" );


        int matchedOpenDowndifference=0;

        int matchedOpenHighdifference=0;

        int totalOpenHigh=0;

        totalCount=0;

        noScrip2upMove=0;

        for(int i=startCountat;i<tickerList1.size();i++){
			totalCount+=1;
			if((i+adder)<tickerList2.size()){
				tick1=(Tick)tickerList1.get(i);
				tick2=(Tick)tickerList2.get(i+adder);


				if(tick2.getPercentageDiffPrevGainOnClose()>minMove){
					noScrip2upMove+=1;
					//if(tick1.getPercentageDiffPrevGainOnClose()>0.0){
					if(tick1.getPercentageDiffAtOpen()>0.7){
						totalOpenHigh+=1;
                       if(tick1.getPercentageDiffOpenLow()<-(0.3)){
                    	   //minGain=tick1.getPercentageDiffPrevGainMax();
                    	   matchedOpenDowndifference+=1;
                    	  // System.out.println(tick1+" \n "+tick2+"\n");
                       }
                       if(tick1.getPercentageDiffOpenMax()>(0.3)){
                    	   matchedOpenHighdifference+=1;
                       }
					}

				}

			}




		}

        resultBuffer.append(scrip1.getExchange()+":"+scrip1.getName()+" vs ");
        resultBuffer.append(scrip2.getExchange()+":"+scrip2.getName()+"  for Min move "+minMove+"\n ");
        resultBuffer.append("Total Open High Count:"+totalOpenHigh);
       // resultBuffer.append(" "+scrip2.getName()+" upmove - "+noScrip2upMove);
        resultBuffer.append(" , "+scrip1.getName()+" matched Max move - "+matchedOpenHighdifference );
        resultBuffer.append(" , "+scrip1.getName()+" matched Low move - "+matchedOpenDowndifference );
        resultBuffer.append(" ,%age high - "+MathUtil.getPortion((double)matchedOpenHighdifference,(double)totalOpenHigh) );
        resultBuffer.append(" ,%age low - "+MathUtil.getPortion((double)matchedOpenDowndifference,(double)totalOpenHigh) );

        resultBuffer.append("\n" );






		return resultBuffer.toString();


	}

	public  void compareScripCorrelation(String exchange1,String stock1,String exchange2,String stock2,double minMove) throws Exception{
		FinanceUtilDay  fd=new FinanceUtilDay();

		Scrip scrip1=fd.getLatestQuoteList(stock1, exchange1);
		Scrip scrip2=fd.getLatestQuoteList(stock2, exchange2);
		System.out.println(scrip1.getTickers());
		System.out.println(scrip2.getTickers());
		//scrip1.getExchange();
		String result=compareScripCorrelation(scrip1, scrip2,minMove);

		System.out.println(result);



	}

	public  void compareScripCorrelationNextDay(String exchange1,String stock1,String exchange2,String stock2,double minMove) throws Exception{
		FinanceUtilDay  fd=new FinanceUtilDay();

		Scrip scrip1=fd.getLatestQuoteList(stock1, exchange1);
		Scrip scrip2=fd.getLatestQuoteList(stock2, exchange2);
		System.out.println(scrip1.getTickers());
		System.out.println(scrip2.getTickers());
		//scrip1.getExchange();
		String result=compareScripCorrelationNextDay(scrip1, scrip2,minMove);

		System.out.println(result);



	}


	public  String  findStatsForMinMove(Scrip scrip,double point1,double point3,double maxError) throws Exception{


		ArrayList tickerArrayList=scrip.getTickers();

		Tick tick=null;

		int point1Total=0;
		int point1MinPoint3Move=0;
		double minForPoint1=100.0;


		int point1TotalNegative=0;
		int point1MinPoint3MoveNegative=0;
		double minForPoint1Negative=-100.0;

		String result="";





		for(int i=0;i<tickerArrayList.size()-1;i++){
			tick=(Tick)tickerArrayList.get(i);
			//System.out.println(" - "+tick);

			if(tick.getPercentageDiffAtOpen()>point1&&tick.getPercentageDiffAtOpen()<point1+maxError){
				point1Total+=1;
				if(tick.getPercentageDiffOpenMax()>point3){
					point1MinPoint3Move+=1;
					//System.out.println(" positive "+tick);

				}

				if(tick.getPercentageDiffOpenMax()<minForPoint1){
					minForPoint1=tick.getPercentageDiffOpenMax();
					if(minForPoint1==0.0){
					//System.out.println(" positive 0 -"+tick);
					}

				}

			}

			if(tick.getPercentageDiffAtOpen()<(-1*(point1))&&tick.getPercentageDiffAtOpen()>((-point1)-maxError)){
				point1TotalNegative+=1;
				if(tick.getPercentageDiffOpenLow()>-(point3)){
					point1MinPoint3MoveNegative+=1;
					//System.out.println("negative "+tick);


				}else{
					//System.out.println("fail tick"+tick);
				}

				if(tick.getPercentageDiffOpenLow()<minForPoint1){
					minForPoint1Negative=tick.getPercentageDiffOpenLow();

				}

			}



		}//EOW


		result=" Total +ve "+point1+" opens For "+scrip.getExchange()+":"+scrip.getName()+" , "+point1Total+", positives for "+point3 +"move : "+point1MinPoint3Move
		+" Minimum :" +minForPoint1;

		result+=" Total -ve "+point1TotalNegative+", positives: "+point1MinPoint3MoveNegative
		+" Minimum "+minForPoint1Negative;



		return (result);
	}

	public  void findForllASX(double point1,double point3,double maxError) throws Exception{

		ArrayList alAsxList=null;

		alAsxList=StockMasterUtil.asxStocks;



		StockInfoMaster stockMaster=null;

		FinanceUtilDay fd=new FinanceUtilDay();

		BufferedWriter bwriter=new BufferedWriter(new FileWriter("D:\\fin_base\\asx_minpointmove.txt"));

		String currString=null;

		for(int i=0;i<alAsxList.size();i++){
			stockMaster=(StockInfoMaster)alAsxList.get(i);

           try{
            if(i>1439){
			//fd.updateQuotes(stockMaster.getName().toUpperCase(),stockMaster.getExchange().toUpperCase());
            }
           }catch (Exception e) {
			// TODO: handle exception
		}

			Scrip scrip=fd.getScripData(stockMaster.getName().toUpperCase(),stockMaster.getExchange().toUpperCase());

			try{

			currString=findStatsForMinMove(scrip,point1,point3,maxError);
			}catch (Exception e) {
				// TODO: handle exception
			}

			System.out.println(currString);

			bwriter.write(currString+"\r\n");
		}//

		bwriter.close();


	}



	public static void main(String[] args) throws Exception{
		//roughCalculation();

		System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 6.0; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.16 Safari/534.24");

		FinanceUtilDay fd=new FinanceUtilDay();

		fd.updateQuotes("BHP","ASX");

		Scrip scrip=fd.getScripData("NCM","ASX");

		ScripCalculations sCalc=new ScripCalculations();

		System.out.println(sCalc.findStatsForMinMove(scrip,point1,point3,maxError));


		//findForllASX();
		//compareScripCorrelation("ASX", "NCM", "PINK","NCMGY",1.7);
		//compareScripCorrelation("ASX", "NCM", "INDEXDJX","DJUSPM",1.0);
		//compareScripCorrelation("ASX", "BHP", "NYSE","BHP",1.5);
		//compareScripCorrelation("NSE", "INFY", "NASDAQ","NASDAQ",0.5);
		//compareScripCorrelation("NASDAQ", "INFY", "NSE","INFY",0.5);
	}

	public static double point3=.3;
	public static double maxError=.3;
	public static double point1=.1;
	public static double point5=.7;


}
